﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;

using ERPStore.Extensions;
using CloudSoft.Workflows;

using CloudSoft.Extensions;

namespace ERPStore.Exporter.Workflows.Activities
{
	public sealed class CreateElement : CodeActivity
	{
		public InArgument<Providers.IExport> ExportArgument { get; set; }
		public InArgument<ERPStore.Models.Product> Product { get; set; }
		public InArgument<List<ERPStore.Models.ProductStockInfo>> ProductStockInfoList { get; set; }
		
		protected override void Execute(CodeActivityContext context)
		{
			var export = context.GetValue(ExportArgument);
			var product = context.GetValue(Product);
			var productStockInfoList = context.GetValue(ProductStockInfoList);

			var productStockInfo = productStockInfoList.FirstOrDefault(i => i.ProductCode == product.Code);

			// Delete possible doublons
			if (!export.ProductIdList.Contains(product.Id))
			{
				export.AddElementToDocument(product, productStockInfo);
				export.ProductIdList.Add(product.Id);
				export.Settings.ProductCount++;
			}

			var eventPublisher = context.GetService<EventBrokR.IPublisher>();
			eventPublisher.PublishAsync(new ERPStore.Events.GlobalEvent()
			{
				EventName = "ProductAddedToComparatorProductList",
				Source = new { Product = product, LeadSource = export.LeadSource },
			});

		}
	}
}
